package com.tigercel.xiangchengyun.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Message
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.tigercel.xiangchengyun.utils.ActivityStackManager
import com.tigercel.xiangchengyun.utils.BaseHandler
import com.tigercel.xiangchengyun.utils.Global

import java.lang.ref.WeakReference

abstract class BaseActivity : AppCompatActivity() {
    abstract val mContentLayoutResouredId: Int
    lateinit var mContext: Context
//    private var handler = BaseHandler(Handler.Callback { message ->
//        handleMsg(message)
//        true
//    })


    private var handler: BaseHandler = @SuppressLint("HandlerLeak")
    object : BaseHandler() {
        override fun dispatchMessage(msg: Message) {
            handleMsg(msg)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (mContentLayoutResouredId != 0) setContentView(mContentLayoutResouredId) else createContentView()
        mContext = this
        //设置竖屏幕
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        ActivityStackManager.getInstance().addActivity(WeakReference(this))

        addSelf()

        init()

        initViews()

        loadData()
    }

    open fun createContentView(): View {
        throw UnsupportedOperationException("NO ContentView ID")
    }


    open fun initViews() {

    }

    /***
     * 用于在初始化View之前做一些事
     */
    open fun init() {}

    /***
     * 加载数据
     */
    open fun loadData() {}

    override fun onResume() {
        super.onResume()
        Global.setContext(this)
    }

    /**
     * 封装对消息的处理逻辑
     */
    open fun handleMsg(msg: Message) {}

    /**
     * 将handler加入到baseHandler集合中； OnCreate的时候调用
     */
    private fun addSelf() {
        this.handler.addSelf(handler)
    }

    /**
     * 将handler从baseHandler集合中移除; onDestory时候调用
     */
    private fun removeSelf() {
//        handler.removeCallbacksAndMessages(null)
        this.handler.removeSelf(handler)
    }

    override fun onDestroy() {
        super.onDestroy()
        removeSelf()
        ActivityStackManager.getInstance().removeActivity(WeakReference(this))
    }
}
